<template>
	<view class="purchase-wrap flex-column">
		<uv-navbar :title="title" bg-color="#fff" :placeholder='true' leftIconSize="20px" leftIconColor="#313C56"
			:autoBack='true' titleStyle="font-size: 16px;font-weight: 500;color: #313c56;" />

		<view class="content">
			<view class="title">
				请选择{{ detail }}形象卡片
			</view>
			<view class="card-list">
				<uv-radio-group size="16" v-model="radiovalue" class="list-wrap">
					<uv-radio iconPlacement="right" class="item flex-column flex-between flex-items-center"
						v-for="(item,index) in nftList" :key="index" :label="item.id" :name="item.id" @change="check(item.id,item)">
						<view class="card-bg">
							<image :src="item.nftUrl" mode=""></image>
						</view>
					</uv-radio>
				</uv-radio-group>
			</view>
			<view class="tips">
				说明：购买数字游民NFT之后，拥有接单的身份后续随着信用等级提升，可接更多类型的任务
			</view>
			<view class="money-wrap flex-row flex-end flex-items-center">
				<text>金额：</text>
				<text class="money"> {{checkedVal ?.amount}}</text>
				<text class="unit">{{checkedVal ?.unit}}</text>
			</view>
		</view>
		<view class="toolbar" :style="{height: $uv.addUnit(toolbarHeight)}">
			<view class="flex-row flex-center flex-items-center" style="width:100%;height: 68px; ">
				<view class="confirm flex-row-center" @click="confirmBuy()">
					确认购买
				</view>
			</view>
		</view>
    <uv-popup ref="successPopup" :closeOnClickOverlay="false" :safeAreaInsetBottom="false" round='10px'>
      <view class="flex-column-center" style="background-color: white; height: 86px; width: 279px;">
        <text class="font-18 font-weight-medium" style="color: #313C56;">NFT 购买成功</text>
        <text class="font-14 font-weight-regular"
              style="color: #6B7885; margin-top: 3px;">尽情的畅游在数字游民的海洋吧...</text>
      </view>
    </uv-popup>
		<toast ref="toast"></toast>
	</view>
</template>

<script>
import {getNftList, nftMint, projectPay} from "../../api";

  export default {
		data() {
			return {
				title: '购买数字游民 NFT',
				detail: '购买数字游民 NFT',
				type: 1,
        nftUrl: '',
        amount: '',
        id: '',
				radiovalue: 1,
        nftList: [],
        // 主网
        spxContractAddr: '0x212fACFf93f0830Ed39229fa55615173C3AC98C5', // spx 合约地址
        usdtContractAddr: '0x55d398326f99059fF775485246999027B3197955', // usdt 代币地址
        abi: [
          // erc 20
          'function name() public view returns (string memory)', //  name
          'function symbol() public view returns (string memory)', // 代币
          'function decimals() external view returns (uint8)', // 单位
          'function initialSupply() external view returns (uint256)', // 初始发行量
          'function totalSupply() external view returns (uint256)', // 总供给
          'function balanceOf(address account) external view returns (uint256)', // 获取余额
          'event Transfer(address indexed from, address indexed to, uint256 value)', // 转账事件
          'function approve(address spender, uint256 amount) public returns (bool)', // 授权
          // 合约
          'function liquidityMint() public returns (bool)', // LP提取
          'function getLpClaim(address account) public view returns (uint256)', // 查询 LP 可提取余额
          'function buyNFTCard(uint256 amountRora, uint256 amountUsd, uint256 random) public returns (bool)', // 购买
          // spx 相关 1, 铸造获取身份 2, 发布任务 3, 确认支付
          'function mintNft(uint256 mint) public returns (bool)',
          'function publish(address nomad, uint256 amount, uint256 stage, uint256 random) public returns (bool)',
          'function dislodge(uint256 random, address nomad) public returns (bool)',
        ],
			};
		},
    onLoad(info) {
      if( info.id  == 1){
        this.detail = "BOSS"
      } else {
        this.detail = "游民"
      }
      this.type = info.id
      this.getProject(info.id)
    },

		computed: {
			checkedVal() {
				return this.nftList.filter(item => item.id === this.radiovalue) ?.[0]
			},
		},

		methods: {
      getProject(id) {
        let params = {
          type: id
        }
        getNftList(params).then((data) => {
            this.nftList = data
        }).catch((e) => {})
      },

      async confirmBuy() {
        uni.showLoading({
          title: '支付中,请等待...',
          mask:true
        })
        let id = this.id
        let nftUrl = this.nftUrl
        let amount = this.amount
        if(id && nftUrl && amount){
          try {
            await this.mintNft_(this.type);
            await this.mint_(this.type, nftUrl);
            setTimeout(function() {
              uni.hideLoading()
            }, 50)
            this.$refs.successPopup.open()
            setTimeout(() => {
              this.$refs.successPopup.close()
              uni.navigateTo({
                url: '/pages/wallet/wallet'
              })
            }, 2500);
          }catch (error){
            this.$refs.toast.show({msg: '支付失败, 请检查SPX余额!'})
          }
        } else {
          this.$refs.toast.show({msg: '请选择对应的 NFT!'})
        }
        setTimeout(function() {
          uni.hideLoading()
        }, 50)
			},

      // 发布任务合约支付
      async mintNft_(type) {
        const tc = await this.$web3.getSingerContract(this.spxContractAddr, this.abi);
        return await tc.mintNft(type);
      },

      async mint_(type, nftUrl) {
        let params = {
          type: type,
          url: nftUrl,
        }
        await nftMint(params).then((data) => {
        }).catch((res) => {})
      },

      check(val, item) {
				this.radiovalue = val
				this.amount = item.amount
				this.nftUrl = item.nftUrl
				this.id = item.id
			}
		}
	}
</script>

<style lang="scss" scoped>
	.purchase-wrap {
		height: 100vh;

		.content {
			flex: 1;
			padding: 16px;

			.title {
				font-size: 16px;
				color: #313C56;
				margin-bottom: 8px;
			}

			.list-wrap {
				display: flex;
				justify-content: space-between;

				.item {
					margin-bottom: 24px;
					width: 98px;
					display: flex;
					flex-direction: column !important;
					padding-bottom: 20px;
					position: relative;

					::v-deep .uv-radio__icon-wrap {
						position: absolute;
						bottom: 0;
					}
				}

				.card-bg {
					box-sizing: border-box;
					overflow: hidden;
					width: 94px;
					height: 126px;
					border-radius: 8px;
					border: 1px solid #F8D9AB;

					image {
						width: 100%;
						height: 100%;
					}
				}

			}

			.tips {
				font-size: 14px;
				color: #6B7885;
			}

			.money-wrap {
				margin-top: 48px;
				font-size: 14px;
				color: #6B7885;

				.money {
					font-size: 24px;
					font-family: DIN, DIN;
					font-weight: 500;
					color: #313C56;
					margin: 0  4px;
				}
			}
		}

		.toolbar {
			.confirm {
				width: 303px;
				height: 44px;
				background: #EB7520;
				box-shadow: 0px 1px 2px 0px rgba(16, 24, 40, 0.05);
				border-radius: 80px 80px 80px 80px;
				font-size: 16px;
				color: #FFFFFF;
			}
		}
	}
</style>